/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.logmanage.logic;

import cn.net.greenet.logmanage.logic.bean.AckInComingLogBean;
import cn.net.greenet.logmanage.logic.bean.AckOutGoingLogBean;
import cn.net.greenet.logmanage.logic.bean.DPIEndPointBean;
import cn.net.greenet.logmanage.logic.bean.MessageInComingLogBean;
import cn.net.greenet.logmanage.logic.bean.MessageOutGoingLogBean;
import cn.net.greenet.logmanage.logic.common.DBUtils;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class LogManageService {

    private Dao<DPIEndPointBean, Integer> DPIEndPointBeanDao;
    private Dao<MessageOutGoingLogBean, Long> MessageOutGoingLogDao;
    private Dao<AckInComingLogBean, Long> ackInComingLogDao;
    private Dao<MessageInComingLogBean, Long> MessageInComingLogDao;
    private Dao<AckOutGoingLogBean, Long> ackOutGoingLogDao;

    public LogManageService(ConnectionSource connectionSource) throws SQLException {
        this.DPIEndPointBeanDao = DaoManager.createDao(connectionSource, DPIEndPointBean.class);
        this.MessageOutGoingLogDao = DaoManager.createDao(connectionSource, MessageOutGoingLogBean.class);
        this.ackInComingLogDao = DaoManager.createDao(connectionSource, AckInComingLogBean.class);
        this.MessageInComingLogDao = DaoManager.createDao(connectionSource, MessageInComingLogBean.class);
        this.ackOutGoingLogDao = DaoManager.createDao(connectionSource, AckOutGoingLogBean.class);
    }

    /**
     * 获取设备列表信息
     *
     * @return
     */
    public List<DPIEndPointBean> getDeviceList() {
        try {
            return DPIEndPointBeanDao.queryForAll();
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 根据设备ID来查询策略发送日志
     * @param deviceId 设备ID
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param pageCount 每页显示条数
     * @param page 当前页码
     * @param MessageType 策略类型
     * @param MessageNo 策略编号
     * @return 
     */
    public Map<MessageOutGoingLogBean, AckInComingLogBean> getStrategySendLogByDeviceId(int deviceId, long startTime, long endTime, long pageCount, long page, String MessageType, String MessageNo) {
        Map<MessageOutGoingLogBean, AckInComingLogBean> result = null;
        try {
            // 获取符合条件的MessageOutGoingLog
            QueryBuilder<MessageOutGoingLogBean, Long> messageOutQB = MessageOutGoingLogDao.queryBuilder();
            Where<MessageOutGoingLogBean, Long> where = messageOutQB.where();
            where.eq(MessageOutGoingLogBean.DPI_ENDPOINT_BEAN_ID, deviceId);
            where.and();
            where.between(MessageOutGoingLogBean.SEND_START_TIME, new Timestamp(startTime), new Timestamp(endTime));
            if (MessageType != null) {
                where.and();
                where.eq(MessageOutGoingLogBean.MESSAGE_TYPE, MessageType);
            }
            if (MessageNo != null) {
                where.and();
                where.eq(MessageOutGoingLogBean.MESSAGE_NO, Integer.parseInt(MessageNo));
            }
            messageOutQB.offset((page - 1) * pageCount).limit(pageCount);
            result = queryStrategySendLog(messageOutQB);
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }

        return result;
    }

    private Map<MessageOutGoingLogBean, AckInComingLogBean> queryStrategySendLog(QueryBuilder<MessageOutGoingLogBean, Long> messageOutQB) {
        Map<MessageOutGoingLogBean, AckInComingLogBean> result = new HashMap();
        try {
            List<MessageOutGoingLogBean> sendMessages = MessageOutGoingLogDao.query(messageOutQB.prepare());

            if (sendMessages != null) {
                Iterator<MessageOutGoingLogBean> it = sendMessages.iterator();
                while (it.hasNext()) {
                    try {
                        MessageOutGoingLogBean message = it.next();
                        DPIEndPointBeanDao.refresh(message.getDpi());

                        // 获取对应的接收Ack
                        QueryBuilder ackQB = ackInComingLogDao.queryBuilder();
                        ackQB.where().eq(AckInComingLogBean.MESSAGE_TYPE, message.getMessageType())
                            .and()
                            .eq(AckInComingLogBean.MESSAGE_NO, message.getMessageNo())
                            .and()
                            .eq(AckInComingLogBean.MESSAGE_SEQUENCE_NO, message.getMessageSequenceNo());
                        AckInComingLogBean ack = ackInComingLogDao.queryForFirst(ackQB.prepare());
                        result.put(message, ack);
                    } catch (SQLException ex) {
                        Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result.size() > 0 ? result : null;
    }

    /**
     * 根据设备IP查询策略发送日志
     * @param ip 设备IP
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param pageCount 每页显示条数
     * @param page 当前页码
     * @param MessageType 策略类型
     * @param MessageNo 策略编号
     * @return 
     */
    public Map<MessageOutGoingLogBean, AckInComingLogBean> getStrategySendLogByDeviceIP(String ip, long startTime, long endTime, long pageCount, long page, String MessageType, String MessageNo) {
        Map<MessageOutGoingLogBean, AckInComingLogBean> result = null;
        try {
            QueryBuilder dpiQB = DPIEndPointBeanDao.queryBuilder();
            dpiQB.where().eq(DPIEndPointBean.MASTER_IP, ip);

            QueryBuilder messageOutQB = MessageOutGoingLogDao.queryBuilder();
            Where<MessageOutGoingLogBean, Long> where = messageOutQB.where().between(MessageOutGoingLogBean.SEND_START_TIME, new Timestamp(startTime), new Timestamp(endTime));
            if (MessageType != null) {
                where.and();
                where.eq(MessageOutGoingLogBean.MESSAGE_TYPE, MessageType);
            }
            if (MessageNo != null) {
                where.and();
                where.eq(MessageOutGoingLogBean.MESSAGE_NO, Integer.parseInt(MessageNo));
            }
            messageOutQB.offset((page - 1) * pageCount).limit(pageCount);
            messageOutQB.leftJoin(dpiQB);
            result = queryStrategySendLog(messageOutQB);
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    private Map<MessageInComingLogBean, AckOutGoingLogBean> queryStrategyReceiveLog(QueryBuilder<MessageInComingLogBean, Long> messageInQB) {
        Map<MessageInComingLogBean, AckOutGoingLogBean> result = new HashMap();
        try {
            List<MessageInComingLogBean> receiveMessages = MessageInComingLogDao.query(messageInQB.prepare());

            if (receiveMessages != null) {
                Iterator<MessageInComingLogBean> it = receiveMessages.iterator();
                while (it.hasNext()) {
                    try {
                        MessageInComingLogBean message = it.next();
                        DPIEndPointBeanDao.refresh(message.getDpi());

                        // 获取对应的回复ACK
                        QueryBuilder ackQB = ackOutGoingLogDao.queryBuilder();
                        ackQB.where().eq(AckOutGoingLogBean.INCOMING_MESSAGE_LOG_ID, message.getId());
                        AckOutGoingLogBean ack = ackOutGoingLogDao.queryForFirst(ackQB.prepare());
                        result.put(message, ack);
                    } catch (SQLException ex) {
                        Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result.size() > 0 ? result : null;
    }

    /**
     * 根据设备ID查询策略接收日志
     * @param id 设备ID
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param pageCount 每页显示条数
     * @param page 当前页码
     * @param MessageType 策略类型
     * @param MessageNo 策略编号
     * @return 
     */
    public Map<MessageInComingLogBean, AckOutGoingLogBean> getStrategyReceiveLogByDeviceId(int id, long startTime, long endTime, long pageCount, long page, String MessageType, String MessageNo) {
        Map<MessageInComingLogBean, AckOutGoingLogBean> result = null;
        try {
            QueryBuilder<MessageInComingLogBean, Long> messageInQB = MessageInComingLogDao.queryBuilder();
            Where<MessageInComingLogBean, Long> where = messageInQB.where();
            where.eq(MessageInComingLogBean.DPI_ENDPOINT_BEAN_ID, id);
            where.and();
            where.between(MessageInComingLogBean.RECEIVE_TIME, new Timestamp(startTime), new Timestamp(endTime));
            if (MessageType != null) {
                where.and();
                where.eq(MessageInComingLogBean.MESSAGE_TYPE, MessageType);
            }
            if (MessageNo != null) {
                where.and();
                where.eq(MessageInComingLogBean.MESSAGE_NO, Integer.parseInt(MessageNo));
            }
            messageInQB.offset((page - 1) * pageCount).limit(pageCount);
            result = queryStrategyReceiveLog(messageInQB);
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * 根据设备IP查询策略接收日志
     * @param ip 设备IP
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param pageCount 每页显示条数
     * @param page 当前页码
     * @param MessageType 策略类型
     * @param MessageNo 策略编号
     * @return 
     */
    public Map<MessageInComingLogBean, AckOutGoingLogBean> getStrategyReceiveLogByDeviceIP(String ip, long startTime, long endTime, long pageCount, long page, String MessageType, String MessageNo) {
        Map<MessageInComingLogBean, AckOutGoingLogBean> result = null;
        
        try {
        QueryBuilder<DPIEndPointBean, Integer> dpiQB = DPIEndPointBeanDao.queryBuilder();
        dpiQB.where().eq(DPIEndPointBean.MASTER_IP, ip);
        
        QueryBuilder<MessageInComingLogBean, Long> messageInQB = MessageInComingLogDao.queryBuilder();
        Where<MessageInComingLogBean, Long> where = messageInQB.where();
        where.between(MessageInComingLogBean.RECEIVE_TIME, new Timestamp(startTime), new Timestamp(endTime));
        if (MessageType != null) {
            where.and();
            where.eq(MessageInComingLogBean.MESSAGE_TYPE, MessageType);
        }
        if (MessageNo != null) {
            where.and();
            where.eq(MessageInComingLogBean.MESSAGE_NO, Integer.parseInt(MessageNo));
        }
        messageInQB.offset((page - 1) * pageCount).limit(pageCount);
        messageInQB.leftJoin(dpiQB);
        result = queryStrategyReceiveLog(messageInQB);
        } catch (SQLException ex) {
            Logger.getLogger(LogManageService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
}
